package com.df.demo;

import com.df.common.IMsg;
import com.df.common.MapThread;
import com.df.common.Player;
import com.df.common.Point;
import com.df.msgs.Req_Login;
import com.df.msgs.Req_Move;
import com.df.msgs.Resp_Login;
import io.netty.channel.Channel;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import io.netty.util.Attribute;

import java.util.UUID;

public class MsgHandlers {
    private MsgHandlers() {}
    private static MsgHandlers instance = new MsgHandlers();
    public static MsgHandlers getInstance() {
        return instance;
    }

    public void dispatch(Channel channel,IMsg msg) {
        if (msg instanceof Req_Login) {
            req_login(channel,msg);
            return;
        }
        Attribute<String> attr = channel.attr(MapThread.uidKey);
        String playerId = attr.get();
        if (msg instanceof Req_Move) {
            req_move(channel,playerId,msg);
            return;
        }
    }

    private void req_move(Channel channel, String playerId, IMsg msg) {
        Player player = MapThread.getInstance().players.get(playerId);
        if(player == null) {
            return;
        }
        Req_Move move = (Req_Move) msg;
        if(player.getPos().equals(new Point(move.x,move.y))){
            return;
        }
        Point point = new Point();
        point.setX(move.x);
        point.setY(move.y);
        player.points.add(point);
    }

    public void req_login(Channel channel,IMsg msg){
        Resp_Login resp = new Resp_Login();
        String uid = UUID.randomUUID().toString();
        resp.setName(uid);
        Player player = new Player();
        player.setName(uid);
        System.out.println("登录用户:" + player.getName());
        Attribute<String> attr = channel.attr(MapThread.uidKey);
        attr.set(uid);
        MapThread.getInstance().players.put(uid,player);
        sendMsg(channel,resp);
    }


    public void sendMsg(Channel channel,IMsg msg){
        if(channel==null || !channel.isActive() ||!channel.isOpen()){
            return;
        }
        String msgStr = msg.toMsgStr();
        TextWebSocketFrame frame = new TextWebSocketFrame(msgStr);
        channel.writeAndFlush(frame);
    }
}
